

interface IItem
{
    fn: Function,
    ts: unknown
}
export class EventManager  {
    private static instance:EventManager=null;
    static get Instance()
    {
        return this.instance?this.instance:(this.instance= new EventManager(),this.instance);
    }
    private eventDic: Map<string, IItem[]> = new Map();

    on(eventName: string, fn: Function, ts?: unknown) {
        if (this.eventDic.has(eventName)) {
            this.eventDic.get(eventName).push({fn,ts});
        }
        else {
            this.eventDic.set(eventName, [{fn,ts}]);
        }

    }

    off(eventName: string, fn: Function, ts?: unknown) {
        if (this.eventDic.has(eventName)) {
            const index = this.eventDic.get(eventName).findIndex(({fn,ts}) => (fn === fn)&&(ts === ts));
            index>-1?this.eventDic.get(eventName).splice(index,1):null;
        }
    }

    emit(eventName: string,...args:unknown[])
    {
        if (this.eventDic.has(eventName)) 
        {
            this.eventDic.get(eventName).forEach(({fn,ts}) => {
                   ts?fn.apply(ts,args):fn(...args);
            })
        }
    }
    clear()
    {
        this.eventDic.clear();
    }
}

